package team.bluepen.order.web.servlet;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.hdfs.HdfsManager;
import team.bluepen.order.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件删除
 * @author Kai
 */
@WebServlet(name = "FileDeleteServlet", urlPatterns = "/api/file/delete")
public class FileDeleteServlet extends BaseServlet {
    public static final String TYPE_PARAM = "type";
    public static final String PATH_PARAM = "path";


    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter(TYPE_PARAM);
        String path = req.getParameter(PATH_PARAM);
        setJsonHeader(resp);
        if (StringUtil.isEmpty(type)) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_NULL,
                            "type parameter missing.")
                    .toCodePack());
            return;
        }

        if ("all".equalsIgnoreCase(type)) {
            HdfsManager.getInstance().delete(Constant.TEMP_DIRECTORY);
            ErrorCode state = HdfsManager.getInstance().delete(Constant.UPLOAD_DIRECTORY);
            if (!state.getState()) {
                writeJson(resp, new ErrorPack(state, state.toString()).toCodePack());
                return;
            }
        } else if ("file".equalsIgnoreCase(type)) {
            if (StringUtil.isEmpty(path)) {
                writeJson(resp, new ErrorPack(ErrorCode.ERROR_NULL,
                        "path parameter missing.")
                        .toCodePack());
                return;
            }
            ErrorCode state = HdfsManager.getInstance().delete(path);
            if (!state.getState()) {
                writeJson(resp, new ErrorPack(state, state.toString()).toCodePack());
                return;
            }
        } else if ("output".equalsIgnoreCase(type)) {
            ErrorCode state = HdfsManager.getInstance().delete(Constant.OUTPUT_DIRECTORY);
            if (!state.getState()) {
                writeJson(resp, new ErrorPack(state, state.toString()).toCodePack());
                return;
            }
        }
        writeJson(resp, new ErrorPack(ErrorCode.SUCCESS, "SUCCESS").toCodePack());
    }

}
